package com.retail.member.client.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.retail.core.entity.result.Result;
import com.retail.member.client.AdminVerifyClient;
import com.retail.member.entity.request.VerifOrderRequest;
import com.retail.member.entity.request.VerifyOrderRequest;
import com.retail.order.entity.request.SysAdminVerifyRequest;
import com.retail.order.entity.vo.RetailSettleOrderVo;
import com.retail.order.entity.vo.SysAdminVerifyDetailVo;
import com.retail.order.entity.vo.SysAdminVerifyVo;
import com.retail.order.enums.TiXianFlagEnums;
import com.retail.order.service.RetailSettleOrderService;
import com.retail.order.service.SysAdminVerifyDetailService;
import com.retail.order.service.SysAdminVerifyService;
import com.retail.setting.entity.vo.RetailFxLevelVo;
import com.retail.setting.service.RetailFxLevelService;
import com.retail.shop.enums.ExamineVerifyEnums;
import com.retail.shop.service.RetailShopService;
import com.retail.system.entity.vo.AdminVo;
import com.retail.system.service.AdminService;
import com.retail.wxchat.entity.vo.RetailWxGetMoneyVo;
import com.retail.wxchat.mapper.RetailWxGetMoneyMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class AdminVerifyClientImpl implements AdminVerifyClient {

    private final RetailSettleOrderService retailSettleOrderService;

    private final AdminService adminService;

    private final SysAdminVerifyDetailService sysAdminVerifyDetailService;

    private final SysAdminVerifyService sysAdminVerifyService;

    private final RetailFxLevelService retailFxLevelService;

    private final RetailWxGetMoneyMapper retailWxGetMoneyMapper;

    public AdminVerifyClientImpl(RetailSettleOrderService retailSettleOrderService, AdminService adminService,  SysAdminVerifyDetailService sysAdminVerifyDetailService, SysAdminVerifyService sysAdminVerifyService, RetailFxLevelService retailFxLevelService, RetailWxGetMoneyMapper retailWxGetMoneyMapper) {
        this.retailSettleOrderService = retailSettleOrderService;
        this.adminService = adminService;
        this.sysAdminVerifyDetailService = sysAdminVerifyDetailService;
        this.sysAdminVerifyService = sysAdminVerifyService;
        this.retailFxLevelService = retailFxLevelService;
        this.retailWxGetMoneyMapper = retailWxGetMoneyMapper;
    }

    @Override
    public Result<List<SysAdminVerifyDetailVo>> toBeVerifyOrders(String adminId) {
        List<SysAdminVerifyDetailVo> ret = recyVerifDetail(adminId, 1);
        return Result.success(ret);
    }

    @Override
    public Result<Integer> verifyOrder(VerifyOrderRequest request) {
        Long adminId = request.getAdminId();
        // 订单信息
        List<SysAdminVerifyDetailVo> orderDetails = request.getOrderDetails();
        // 用户信息
        AdminVo adminVo = adminService.getModel(adminId);
        // 分销等级
        List<RetailFxLevelVo> retailFxLevelVos = retailFxLevelService.getAllModel();

        RetailFxLevelVo matchFxLevel = getMatchFxLevel(adminVo, retailFxLevelVos);

        // 得到可用汇率
        RetailWxGetMoneyVo retailWxGetMoneyVo = retailWxGetMoneyMapper.getUseModel();

        if (ObjectUtil.isEmpty(retailWxGetMoneyVo)) {
            return Result.fail("不能核销订单，请联系系统管理员【汇率问题】");
        }

        Date date = adminVo.getOwnerShopLastTime();
        if (new Date().getTime() > DateUtil.offset(date, DateField.DAY_OF_YEAR, retailWxGetMoneyVo.getRangeDay()).getTime()) {
            return Result.fail("不能核销订单，请联系系统管理员【核销时限问题】");
        }

        Long verifCount = sysAdminVerifyDetailService.verifyOrder(adminVo, matchFxLevel, retailWxGetMoneyVo, orderDetails);

        return Result.success(verifCount);
    }

    /**
     * 得到数据
     *
     * @param request
     * @return
     */
    @Override
    public Result<Integer> verifyOrder(VerifOrderRequest request) {
        Long adminId = request.getAdminId();
        // 订单信息
        List<SysAdminVerifyDetailVo> orderDetails = batchOrderConvertVerify(adminId, request.getOrders());
        // 用户信息
        AdminVo adminVo = adminService.getModel(adminId);
        // 分销等级
        List<RetailFxLevelVo> retailFxLevelVos = retailFxLevelService.getAllModel();

        RetailFxLevelVo matchFxLevel = getMatchFxLevel(adminVo, retailFxLevelVos);

        // 得到可用汇率
        RetailWxGetMoneyVo retailWxGetMoneyVo = retailWxGetMoneyMapper.getUseModel();

        if (ObjectUtil.isEmpty(matchFxLevel)) {
            return Result.fail("不符合系统核心标准，不允许进行核销【分销等级问题】");
        }

        if (ObjectUtil.isEmpty(retailWxGetMoneyVo)) {
            return Result.fail("不能核销订单，请联系系统管理员【汇率问题】");
        }

        Date date = adminVo.getOwnerShopLastTime();
        if (new Date().getTime() > DateUtil.offset(date, DateField.DAY_OF_YEAR, retailWxGetMoneyVo.getRangeDay()).getTime()) {
            return Result.fail("不能核销订单，请联系系统管理员【核销时限问题】");
        }

        Long verifCount = sysAdminVerifyDetailService.verifyOrder(adminVo, matchFxLevel, retailWxGetMoneyVo, orderDetails);

        return Result.success(verifCount);

    }

    @Override
    public Result<SysAdminVerifyVo> verifyDetail(Long hxId) {
        SysAdminVerifyVo sysAdminVerifyVo = sysAdminVerifyService.getModel(hxId);
        List<SysAdminVerifyDetailVo> orderDetails = sysAdminVerifyDetailService.findDetailByVerifyId(sysAdminVerifyVo.getId());
//        orderDetails.forEach(od -> {
//            String orderId = od.getOrderId();
//            RetailSettleOrderVo order = retailSettleOrderService.getModelByOrderId(orderId);
//
//            if (ObjectUtil.isNotEmpty(od.getOrderOwnerId())) {
//                AdminVo adminVo = adminService.getModel(od.getOrderOwnerId());
//                if (ObjectUtil.isNotEmpty(adminVo)) {
//                    od.setOrderOwnerName(adminVo.getName());
//                }
//            }
//            od.setOrder(order);
//        });

//        sysAdminVerifyVo.setOrderDetails(orderDetails);
        return Result.success(sysAdminVerifyVo);
    }


    @Override
    public Result<List<SysAdminVerifyVo>> adminVerifyList(Long adminId) {
        List<SysAdminVerifyVo> res = listAdminStatus(adminId, null);
        return Result.success(res);
    }

    @Override
    public Result<List<SysAdminVerifyVo>> adminVerifyListStatus(SysAdminVerifyRequest request) {
        List<SysAdminVerifyVo> res = listAdminStatus(request.getAdminId(), request.getExamineVerify());
        return Result.success(res);
    }

    public List<SysAdminVerifyVo> listAdminStatus(Long adminId, Integer examineVerify) {
        List<SysAdminVerifyVo> res = sysAdminVerifyService.adminVerifyListStatus(adminId, examineVerify);
        res.forEach(r -> {
            AdminVo adminVo = adminService.getModel(r.getAdminId());
            if (ObjectUtil.isNotEmpty(adminVo)) {
                r.setAdminName(adminVo.getName());
            }
            
            r.setExamineVerifyName(ExamineVerifyEnums.getStatusValues(r.getExamineVerify()));
            r.setTixianFlagName(TiXianFlagEnums.getStatusValues(r.getTixianFlag()));
        });
        return res;
    }

    private List<SysAdminVerifyDetailVo> batchOrderConvertVerify(Long adminId, List<RetailSettleOrderVo> orders) {
        List<SysAdminVerifyDetailVo> res = new ArrayList<>();
        orders.forEach(order -> {
            SysAdminVerifyDetailVo detail = orderConvertOrderVerify(order, adminId, order.getOrderLevel());
            res.add(detail);
        });

        return res;

    }

    /**
     * 得到匹配的分销等级
     *
     * @param adminVo
     * @param levels
     * @return
     */
    private RetailFxLevelVo getMatchFxLevel(AdminVo adminVo, List<RetailFxLevelVo> levels) {

        if (adminVo == null || levels.size() == 0) {
            return null;
        }

        AtomicReference<RetailFxLevelVo> matchLevel = new AtomicReference<>();
        // 团队商户数量
        Integer shopCount = ObjectUtil.defaultIfNull(adminVo.getGroupShopCount(), 0);
        for (RetailFxLevelVo retailFxLevelVo : levels) {
            if ((retailFxLevelVo.getGroupStartNum() <= shopCount && retailFxLevelVo.getGroupEndNum() >= shopCount)) {
                matchLevel.set(retailFxLevelVo);
            }
        }

        if (matchLevel.get() == null) {
            for (RetailFxLevelVo level : levels) {
                if ((level.getGroupEndNum() <= shopCount)) {
                    matchLevel.set(level);
                }
            }
        }
        return matchLevel.get();
    }

    private List<SysAdminVerifyDetailVo> recyVerifDetail(String adminId, Integer poiLevel) {
        List<SysAdminVerifyDetailVo> ret = new ArrayList<>();
        List<RetailSettleOrderVo> orderVos = retailSettleOrderService.findOwnerOrderByAdminId(adminId);
        for (RetailSettleOrderVo order : orderVos) {// 判断单子是否核销
            SysAdminVerifyDetailVo detailVo = sysAdminVerifyDetailService.getMaxModelByOrderId(order.getAdminId() + "", order.getOrderId());
            if (ObjectUtil.isEmpty(detailVo) || (ObjectUtil.equal(detailVo.getDelFlag(), 1))) {
                // 当前用户订单
                ret.add(orderConvertOrderVerify(order, Long.parseLong(adminId), poiLevel));
                // 用户1级订单
                List<AdminVo> childAdmins = adminService.childAdminByParentId(order.getAdminId());
                childAdmins.forEach(admin -> {
                    ret.addAll(recyVerifDetail(admin.getId() + "", poiLevel + 1));
                });
            }
        }

        return ret;
    }


    private SysAdminVerifyDetailVo orderConvertOrderVerify(RetailSettleOrderVo orderVo, Long adminId, Integer poiLevel) {
        SysAdminVerifyDetailVo sysAdminVerifyDetailVo = new SysAdminVerifyDetailVo();
//        sysAdminOrderVerifyDetailVo.setVerifyId();
//        sysAdminVerifyDetailVo.setAdminId(adminId);
//        sysAdminVerifyDetailVo.setObjectId(orderVo.getPoiId());
//        sysAdminVerifyDetailVo.setPoiLevel(poiLevel + "");
//        if (ObjectUtil.isNotEmpty(orderVo.getPoiId())) {
//            RetailShopVo retailShopVo = retailShopService.getModelByPoiIdLimmit1(orderVo.getPoiId());
//            if (ObjectUtil.isNotEmpty(retailShopVo)) {
//                sysAdminVerifyDetailVo.setShop(retailShopVo);
//                sysAdminVerifyDetailVo.setPoiName(retailShopVo.getPoiName());
//            }
//        }
//        sysAdminVerifyDetailVo.setOrderId(orderVo.getOrderId() + "");
//        sysAdminVerifyDetailVo.setOrderPrice(orderVo.getReceiptAmount());
//        sysAdminVerifyDetailVo.setOrderOwnerId(orderVo.getAdminId());
////        sysAdminOrderVerificationDetailVo.setId();
//        sysAdminVerifyDetailVo.setDelFlag(DelFlagEnum.NO.getValue());
//        sysAdminVerifyDetailVo.setStatusFlag(StatusFlagEnum.USE.getValue());
//        sysAdminVerifyDetailVo.setCreateUser(orderVo.getAdminId());
////        sysAdminOrderVerificationDetailVo.setCreateTime();
////        sysAdminOrderVerificationDetailVo.setUpdateTime();
////        sysAdminOrderVerificationDetailVo.setRemark("核销");
//        sysAdminVerifyDetailVo.setOrder(orderVo);
        return sysAdminVerifyDetailVo;
    }

    @Override
    public Result getList(Long userId) {
        return Result.success(sysAdminVerifyService.getList(userId));
    }

    @Override
    public Result getModel(Long id) {
        return Result.success(sysAdminVerifyService.getModel(id));
    }
}
